/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ar.com.wholeconsulting.pacc.gui.modelos;


import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;

public class UsuarioCheckboxFinder extends PlainDocument {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1991305648282623923L;
	JComboBox comboBox;
    ComboBoxModel model;
    // flag to indicate if setSelectedItem has been called
    // subsequent calls to remove/insertString should be ignored
    boolean selecting=false;

    public UsuarioCheckboxFinder(final JComboBox comboBox) {
        this.comboBox = comboBox;
        this.model = comboBox.getModel();
    }

    @Override
    public void remove(int offs, int len) throws BadLocationException {
        // return immediately when selecting an item
        if (this.selecting) return;
        super.remove(offs, len);
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        // return immediately when selecting an item
        if (this.selecting) return;
        // insert the string into the document
        super.insertString(offs, str, a);
        // lookup and select a matching item
        Object item = this.lookupItem(this.getText(0, this.getLength()));
        this.setSelectedItem(item);
        // remove all text and insert the completed string
        super.remove(0, this.getLength());
        super.insertString(0, item.toString(), a);
        // select the completed part
        JTextComponent editor = (JTextComponent) this.comboBox.getEditor().getEditorComponent();
        editor.setSelectionStart(offs+str.length());
        editor.setSelectionEnd(this.getLength());
    }

    private void setSelectedItem(Object item) {
        this.selecting = true;
        this.model.setSelectedItem(item);
        this.selecting = false;
    }

    private Object lookupItem(String pattern) {
        // iterate over all items
        for (int i=0, n=this.model.getSize(); i < n; i++) {
            Object currentItem = this.model.getElementAt(i);
            // current item starts with the pattern?
            if (currentItem.toString().startsWith(pattern)) {
                return currentItem;
            }
        }
        // no item starts with the pattern => return null
        return null;
    }

}